﻿using System;
using System.Collections.Generic;
using System.Linq;

using System.Text;
using NETL.Data.Context;
using NETL.Data.Config;
using NETL.Data;
using NETL.Engine.Source;
using NETL.Engine.Transformation;
using NETL.Engine.Destination;
using log4net;

namespace NETL.Engine.Context
{
	public class PipelineFactory
	{
		private ILog myLogger = LogManager.GetLogger(typeof(PipelineFactory));

		public IList<Pipeline> GetActivePipelines()
		{
			List<Pipeline> retValue = new List<Pipeline>();

			using (NetlConfigurationContext ctx = ConfigurationDA.Context())
			{
				foreach (PipelineData pld in ctx.PipelineDatas.Where<PipelineData>(pipeline => pipeline.IsActive == true))
				{
					if (pld.IsActive)
					{
						retValue.Add(BuildPipeline(pld));
					}
				}
			}

			return retValue;
		}

		public Pipeline BuildPipeline(PipelineData pld)
		{
			if (!pld.IsActive)
			{
				myLogger.DebugFormat("Pipeline is not active '{0}', {1}", pld.Name, pld.PipelineId);
				return null;
			}

			myLogger.DebugFormat("Build pipeline '{0}', {1}", pld.Name, pld.PipelineId);

			Pipeline p = new Pipeline();

			foreach (SourceData data in pld.SourceDatas)
			{
				if (!data.IsActive)
				{
					continue;
				}

				IMessageSource s = SourceFactory.Instance().BuildSource(data);
				if (s != null)
				{
					p.Sources.Add(s);
				}
			}

			foreach (PipelineTransformation data in pld.PipelineTransformations.OrderBy(pt => pt.Position))
			{
				ITransformation t = TransformationFactory.Instance().BuildTransformation(data.TransformationData);
				if (t != null)
				{
					p.Transformations.Add(t);
				}
			}

			foreach (DestinationData data in pld.DestinationDatas)
			{
				if (!data.IsActive)
				{
					continue;
				}

				IMessageDestination d = DestinationFactory.Instance().BuildDestination(data);
				if (d != null)
				{
					p.Targets.Add(d);
				}
			}

			return p;
		}
	}
}
